<template>
  <div class="video-player" @click="handleClick">
    <video 
      :src="videoPath"
      :poster="posterPath"
      :id="id" 
      :class="`video-js vjs-default-skin vjs-${fomatScale(screenScale)}`" 
      muted>
      <!-- <source src="" type="video/mp4"> -->
    </video>
  </div>
</template>
  
<script>
import videojs from "video.js";
import "video.js/dist/video-js.css";

export default {
  name: 'videoPlayer',
  components: {},
  props:{
    //组件id
    id:{
      type:String,
    },
    //视频id
    videoId:{
      type:String,
    },
    // 是否自动播放
    isAutoplay: {
      type:Boolean,
      default: false,
    },
    // 播放开始秒
    startSecond: {
      type:Number,
      default: 0,
    },
    // 记录播放时间的间隔秒数
    interval: {
      type:Number,
      default: 5,
    },
    // 视频路径   
    videoPath:{
      type:String,
      default: '',
    },
    // 视频封面路径
    posterPath:{
      type:String,
      default: '',
    },
    // 屏幕比例(宽/高)
    screenScale:{
      type:String,
      default: '16/9',
    },
  },
  data(){
    return {
      timer: null,
      videoInfo: {
        //当前观看的最大时间
        watchMaxTime: 0,
        //是否是第一次观看
        isFirstWatch: true
      },
    }
  },
  created(){
    this.handleClick()
  },
  mounted(){
    this.initVideo()
  },
  beforeDestroy(){
    clearInterval(this.timer)
    this.timer = null
    this.$emit('recordingTime',this.watchMaxTime,this.videoId)
  },
  deactivated(){
    this.$emit('recordingTime',this.watchMaxTime,this.videoId)
  },
  methods:{
    handleClick(){
      try {
          let selection = window.getSelection();
          let range = selection.getRangeAt(0);
          // 使用 range 对象
      } catch (error) {
          // 处理错误
          console.warn('No selection to work with.');
      }
    },
    // 格式化评论比例
    fomatScale(val){
      let arr = ['1/1','4/3','16/9']
      let scale = '4-3'
      if(arr.includes(val)){
        scale = val.split('/').join('-')
      }
      return scale
    },
    initVideo(){
    var that = this;
    const videoBox = document.getElementById(that.id)
    console.log('videoBox',videoBox)
    //判断是否获取到dom，获取到了，那么跳过这，直接videojs初始化
    if (!videoBox) {
      setTimeout(() => {
        this.initVideo(src)//延迟500ms继续执行这个初始化函数，继续判断是否能获取到
      }, 500)
      return
    }
    let player = videojs(document.getElementById(this.id), {
      controls: true,
      autoplay: that.isAutoplay,
      preload: 'auto',
      width: that.width,
      height: that.height,
      fluid: true, //流畅模式
      controlsBar: {
        loop: true,
        playToggle: true,
        currentTimeDisplay:false,// 当前播放时间
        timeDivider: true, // 当前时间和持续时间的分隔符
        durationDisplay: false, // 显示持续时间
        remainingTimeDisplay: true, // 是否显示剩余时间功能
        fullscreenToggle: true, // 是否显示全屏按钮
      }
    }, function () {
      // 间隔固定秒记录播放时间
      let interval = that.interval ? that.interval : 5
      that.timer = setInterval(() => {
        that.$emit('recordingTime',that.videoInfo.watchMaxTime,that.videoId)
      },interval*1000)

      //播放事件改变事件
      this.on('timeupdate', function () {
        //记录视频播放最大的时间
        if (this.currentTime() > that.videoInfo.watchMaxTime) {
          //但如果相差3秒就证明肯定是往后拖时间了 因为正常来说是0.3秒更新一次
          var num = parseFloat(this.currentTime()) - parseFloat(that.videoInfo.watchMaxTime);
          if (num < 1 || that.videoInfo.isFirstWatch) {
            that.videoInfo.watchMaxTime = this.currentTime() //记录已看过的最大时间
          }
        }
      })
      //播放事件 在播放时跳转到上次观看位置和禁止快进支持回退
      this.on('play', function () {
        //第一次触发跳转到上次播放记录时间
        if (that.videoInfo.isFirstWatch) {
          that.videoInfo.isFirstWatch = false;
          //记录最大观看时间
          that.videoInfo.watchMaxTime = that.startSecond
          //将视频播放条跳转到该时间位置
          this.currentTime(that.startSecond);
        } else {
          //不是第一次观看视频的话 只允许回退不允许快进
          //如果当前播放时间大于最大观看时间则跳回最大观看时间
          if (this.currentTime() > that.videoInfo.watchMaxTime) {
            this.currentTime(that.videoInfo.watchMaxTime);
          }
        }
        });
      })
    },
  }
}
</script>

<style scope>
.vjs-duration{
  display: block !important;
}
.vjs-poster{
  width: 0;
  height: 0; 
}

.vjs-button{
  background-color: transparent !important;
  height: 100% !important;
  display: block !important;
  width: 40px !important;
}

button:focus {
  outline: none !important;
}

.vjs-skip-backward-undefined,.vjs-playback-rate,
.vjs-chapters-button,.vjs-skip-forward-undefined,
.vjs-descriptions-button,.vjs-subs-caps-button,
.vjs-audio-button{
  display: none !important;
}

.video-js .vjs-big-play-button{
  color: white !important;
}

</style>
  